<template>
  <div>
    <el-card>
      <el-card>
      <el-date-picker v-model="timeHorizon" value-format="yyyy-MM-dd" type="daterange"
      align="right" unlink-panels range-separator="——" :start-placeholder='$t("Start_time")' :end-placeholder='$t("End_time")'
      :picker-options="pickerOptions" @change = "changeTime">
    </el-date-picker>
    <el-select v-model="listQuery.shopId"   clearable class="filter-item" :placeholder="$t('请选择门店')">
      <el-option v-for="item in shops" :value="item.id" :label="item.name"></el-option>
    </el-select>

    <el-select v-model="listQuery.subscribeId" filterable  clearable class="filter-item" :placeholder="$t('请选择订阅名称')">
      <el-option v-for="item in subscribeList" :value="item.subscribeId" :label="item.subscribeName"></el-option>
    </el-select>

    <el-button class="filter-item"  type="primary" icon="el-icon-search" @click="handleFilter"
      v-permission="['GET /admin/p/lumiere_statistic']">{{$t('Search')}}</el-button>
    </el-card>
    <el-card>
      <el-descriptions class="margin-top" v-model="totalData" :title='$t("概况")' direction="vertical" :column="12"
        :size="size" border>
        <el-descriptions-item :label='$t("订阅总数")'>{{totalData.total}}</el-descriptions-item>
        <el-descriptions-item :label='$t("订阅总人数")'>{{totalData.userTotal}}</el-descriptions-item>
        <el-descriptions-item :label='$t("原商品价格")'>{{"$" + totalData.totalPrice}}</el-descriptions-item>
        <el-descriptions-item :label='$t("点击总数")'> {{totalData.total}}</el-descriptions-item>
        <el-descriptions-item :label='$t("订阅总积分")'>{{totalData.totalPoint}}</el-descriptions-item>
        <el-descriptions-item :label='$t("订单数量")'>{{totalData.orderNum}}</el-descriptions-item>
        <el-descriptions-item :label='$t("商品数量")'>{{totalData.goodsNum}}</el-descriptions-item>
        <el-descriptions-item :label='$t("自提数")'>{{totalData.selfNum}}</el-descriptions-item>
        <el-descriptions-item :label='$t("门店配送数")'> {{totalData.storeNum}}</el-descriptions-item>
        <el-descriptions-item :label='$t("邮寄数")'>{{totalData.mailNum}}</el-descriptions-item>
        <el-descriptions-item :label='$t("订阅价格")'>{{"$" + totalData.basePrice}} </el-descriptions-item>
        <el-descriptions-item :label='$t("损耗金额")'>{{"$" + totalData.lossAmount}}</el-descriptions-item>

      </el-descriptions>
    </el-card>

    <el-card>
      <el-table :data="list" style="width: 100%">
        <el-table-column prop="subscribeName" :label="$t('订阅名称')" width="180">
        </el-table-column>
        <el-table-column prop="total" :label="$t('订阅总数')" width="180">
        </el-table-column>
        <el-table-column prop="userTotal" :label="$t('订阅总人数')" width="180">
        </el-table-column>
        <el-table-column prop="totalPrice" :label="$t('原商品价格')" :formatter="formatPrice" width="200">
        </el-table-column>
        <el-table-column prop="total" :label="$t('点击总数')" width="180">
        </el-table-column>
        <el-table-column prop="totalPoint" :label="$t('订阅总积分')" width="180">
        </el-table-column>
        <el-table-column prop="orderNum" :label="$t('订单总数')">
        </el-table-column>
        <el-table-column prop="goodsNum" :label="$t('商品数量')" width="180">
        </el-table-column>
        <el-table-column prop="selfNum" :label="$t('自提数')" width="180">
        </el-table-column>
        <el-table-column prop="storeNum" :label="$t('门店配送数')">
        </el-table-column>
        <el-table-column prop="mailNum" :label="$t('邮寄数')" width="180">
        </el-table-column>
        <el-table-column prop="basePrice" :label="$t('订阅价格')" :formatter="formatPrice" width="180">
        </el-table-column>
        <el-table-column prop="lossAmount" :formatter="formatPrice" :label='$t("损耗金额")'>
        </el-table-column>

        <el-table-column width="120px" align="center" :label='$t("开始时间")' prop="startTime">
          <template slot-scope="scope">
            <span style="display: block;">{{formatDateTime(scope.row.startTime)}}</span>
            <span style="display: block;">{{formatTime(scope.row.startTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column width="120px" align="center" :label='$t("结束时间")' prop="endTime">
          <template slot-scope="scope">
            <span style="display: block;">{{formatDateTime(scope.row.endTime)}}</span>
            <span style="display: block;">{{formatTime(scope.row.endTime)}}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" align="center" :label="$t('Operate')" width="120"
          class-name="small-padding fixed-width">
          <template slot="header" slot-scope="{row}">
            {{$t('Operate')}}
            <i class="el-icon-setting" style="color: #d35e32"></i>
          </template>
          <template slot-scope="scope">
            <el-button v-permission="['GET /admin/p/lumiere_statistic_detail']" type="info" icon="el-icon-view" plain1
              size="mini" @click="handleDetail(scope.row)">{{$t('Details')}}</el-button>
          </template>
        </el-table-column>

      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
        @pagination="getTypeList" />

    </el-card>
  </el-card>
  </div>
</template>

<script>
  import { statistic, statisticByType,subscribeList } from '../../api/lumiereSubscribeStatistic'
  import { listCountryRegion, listLocationRegion, listSubRegion } from '../../api/region'
  import Pagination from '@/components/Pagination'
  import ElSelectDropdown from 'element-ui/packages/select/src/select-dropdown'
  import BackToTop from '@/components/BackToTop'
  import { allForPerm } from '../../api/shop'

  export default {
    name: 'subscribeStatistic',
    components: { ElSelectDropdown, BackToTop, Pagination },
    data() {
      return {
        total: 0,
        locations: [],
        totalData: {

        },
        list: [],
        shops: [],
        timeHorizon:undefined,
        subscribeList: [],
        listQuery: {
          page: 1,
          limit: 20,
          startTime: undefined,
          endTime: undefined,
          shopId: undefined,
          sort: 'add_time',
          order: 'desc',
          subscribeId:undefined
        },
        regionProps: { multiple: true, value: 'id', label: 'nameEn', emitPath: false },
        isSelectTime: true,
        props: {
          value: 'id',
          label: 'nameEn',
          children: 'children',
          checkStrictly: true
        },
        pickerOptions: {
          shortcuts: [{
            text: this.$t('Yesterday'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('Last_7_days'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('Last_month'),
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }]
        },
      }
    },
    created() {
      // alert(111)
      this.getLocations();
      this.getList();
      this.getTypeList();
      this.getSubscribeList()
      allForPerm().then(response => {
        this.shops = response.data.data.list
      })
    },
    methods: {
      // 获取所有订阅
      getSubscribeList(){
        statisticByType({}).then(res => {
          this.subscribeList = res.data.data.list
          // this.list = response.data.data.list
          // this.total = response.data.data.total
        })
      },
      getList() {
        let param = _.clone(this.listQuery);
        statistic(param).then(response => {
          this.totalData = response.data.data;
        })
      },

      getTypeList() {
        let param = _.clone(this.listQuery);
        statisticByType(param).then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
        })
      },

      getFullDate(targetDate) {
        var D, y, m, d;
        if (targetDate) {
          D = new Date(targetDate);
          y = D.getFullYear();
          m = D.getMonth() + 1;
          d = D.getDate();
        } else {
          y = fullYear;
          m = month;
          d = date;
        }
        m = m > 9 ? m : '0' + m;
        d = d > 9 ? d : '0' + d;
        return y + '-' + m + '-' + d;
      },
      getIndex(index) {
        return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
      },
      handleDetail(row) {
        this.$router.push({
          path: '/subscribe/typeStatisticDetail',
          query: {
            totalData: row,
            startTime: this.listQuery.startTime,
            endTime: this.listQuery.endTime,
            regionId: this.listQuery.regionId
          }
        })
      },
      changeTime(e){
          if(e==null){
            this.listQuery.startTime = undefined
            this.listQuery.endTime = undefined
          }else{
            this.listQuery.startTime = e[0]
            this.listQuery.endTime = e[1]
          }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
        this.getTypeList()
      },
      handleItemChange(val) {
        let step = val.length
        let query = {
          id: val[val.length - 1],
          type: 1
        }
        listSubRegion(query).then(response => {
          let result = this.findObject(this.countrys, val)
          // console.log(result)
          response.data.data.list.forEach(child => {
            if (step <= 1) {
              result.children.push(this._.defaults(child, { children: [] }))
            } else {
              result.children.push(child)
            }
          })
        })
      },
      getLocations() {
        listLocationRegion().then(response => {
          this.locations = response.data.data.list
          if (this.listQuery.regionId && this.listQuery.regionId.length > 0) {
            let p = [];
            this.listQuery.regionId.forEach(id => {
              this.locations.forEach(region => {
                if (region.children && region.children.length > 0) {
                  region.children.forEach(item => {
                    if (item.children && item.children.length > 0) {
                      item.children.forEach(sub => {
                        if (sub.id == id) {
                          let tmp = sub.id;
                          p.push(tmp)
                        }
                      })
                    }
                  })
                }
              })
            })
          }
        })

      },
      // 自定义方法来拆分日期时间字符串
      formatDateTime(value) {
        if (value != undefined) {
          // 创建 Date 对象来解析日期时间字符串
          const date = new Date(value);
          // 获取年月日部分并格式化
          const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
          return formattedDate;
        } else {
          return undefined
        }

      },
      // 自定义方法来拆分日期时间字符串
      formatTime(value) {
        if (value != undefined) {
          // 创建 Date 对象来解析日期时间字符串
          const date = new Date(value);
          // 获取时分秒部分并格式化
          const formattedTime = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
          return formattedTime;
        } else {
          return undefined
        }
      },
      formatPrice(row, column, cellValue) {
        // 在金额前面添加 $ 符号，并返回新的字符串
        return '$' + cellValue;
      }
    },

 }
</script>

<style scoped>

</style>
